<template>
  <div>
    <Breadcrumb :style="{margin: '16px 0'}">
      <BreadcrumbItem>首页</BreadcrumbItem>
      <BreadcrumbItem to="/person">人员管理</BreadcrumbItem>
      <BreadcrumbItem>添加人员</BreadcrumbItem>
    </Breadcrumb>
    <Card>
      <div style="min-height: 650px">
        <Row>
          <Col span="16" offset="4">
            <div style="font-size: 14px;margin-top: 25px;">
              <h4>公司部门</h4>
              <Tree :data="deptData" @on-select-change="checkChange" ></Tree>
            </div>
            <Divider></Divider>
            <Form ref="personData" :model="personData" :rules="personRules">
              <FormItem label="姓名" prop="name">
                <Input v-model="personData.name" placeholder="请输入要添加的人员姓名" />
              </FormItem>
              <FormItem label="手机号" prop="phone">
                <Input v-model="personData.phone" placeholder="请输入手机号码" />
              </FormItem>
              <FormItem label="所属角色" prop="role">
                <Select v-model="personData.role">
                  <Option v-for="role in roleList" :key="role.id" :value="role.id">{{role.roleName}}</Option>
                </Select>
              </FormItem>
              <FormItem>
                <Button type="primary" @click="handleAddUser">提交</Button>
              </FormItem>
            </Form>
          </Col>
        </Row>
      </div>
    </Card>
  </div>
</template>

<script>
import qs from 'qs'
export default {
  data() {

    const validateAccount = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('账号不能为空!'))
      } else {
        this.$axios.post('/bm/opera/sysuser/findSysuser', qs.stringify({
          account: value
        })).then(res => {
          if (res.data.code == 200) {
            callback()
          } else {
            callback(new Error(res.data.description))
          }
        })
      }
    }

    const validateRole = (rule, value, callback) => {
      console.log(value)
      if (value === '') {
        callback(new Error('用户所属角色不能为空！'))
      } else {
        callback()
      }
    }

    return {
      pageno: 1,
      pageSize: 10,
      total: 0,
      resetPwdModal: false,
      personModal: false,
      personList: [],
      columns: [
        {
          title: '#',
          type: 'index'
        }, {
          title: '姓名',
          key: 'userName'
        }, {
          title: '角色',
          key: 'roleName'
        }, {
          title: '账号',
          key: 'account'
        }, {
          title: '操作',
          render: (h, param) => {
            return h('span', [
              h('Button', {
                props: {
                  type: 'primary',
                },
                style: {
                  marginRight: '15px'
                },
                on: {
                  click: () => {
                    this.isEdit = true
                    this.personModal = true
                    this.personData = {
                      userId: param.row.id,
                      name: param.row.userName,
                      phone: param.row.account,
                      role: String(param.row.roldId),
                      status: '1'
                    }
                  }
                }
              }, '编辑'),
              h('Button', {
                props: {
                  type: 'warning'
                },
                on: {
                  click: () => {
                    this.resetPwdModal = true
                    this.personData.userid = param.row.id
                  }
                }
              }, '重置密码')
            ])
          }
        }
      ],
      personData: {
        name: '',
        phone: '',
        role: '',
        status: '1',
        userId: ''
      },
      roleList: [],
      deptData: [],
      pid: '',
      plevel: '',
      personRules: {
        name: [
          {
            required: true,
            message: '姓名不能为空！',
            trigger: 'blur'
          }
        ],
        phone: [
          // {
          //   required: true,
          //   massage: '用户账号不能为空',
          //   trigger: 'blur'
          // },
          {
            required: true,
            validator: validateAccount,
            trigger: 'blur'
          }
        ],
        role: [
          {
            required: true,
            validator: validateRole,
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    checkChange(n, m) {
      console.log(m)
      this.pid = m.id
      this.plevel = m.level
    },
    handleAddUser() {
      // if (this.personData.name == '') {
      //   this.$Message.error('人员姓名不能为空！')
      //   return false
      // }
      // if (this.personData.phone == '') {
      //   this.$Message.error('人员的联系方式不能为空！')
      //   return false
      // }
      // if (this.personData.role == '') {
      //   this.$Message.error('人员的角色不能为空！')
      //   return false
      // }
      this.$refs['personData'].validate((valid) => {
        if (valid) {
          if (this.pid == '' || this.deptLevel == '') {
            this.$Message.error('部门未选择！')
            return false
          }

          this.$axios.post('/bm/opera/sysuser/addSysuser', qs.stringify({
            userName: this.personData.name,
            account: this.personData.phone,
            deptId: this.pid,
            roleId: this.personData.role,
            deptLevel: this.plevel
          })).then(res => {
            if (res.data.code == 200) {
              this.$Message.success('人员添加成功！')
              this.$router.replace('/person')
            } else {
              this.$Message.error(res.data.description)
            }
          }).catch(err => {
            this.$Message.error('网络错误，请稍后重试！')
          })

        } else {
          // this.$Message.error('Fail!');
        }
      })
    },
    getList(url, _this) {
      _this.$axios.get(url).then(res => {
        if (res.data.code == 200) {
          _this.personList = res.data.detail.list
        }
      })
    }
  },
  mounted() {
    const url = '/bm/opera/sysuser/findSysuserPageList?pageNo=' + this.pageno + '&pageSize=' + this.pageSize
    this.$options.methods.getList(url, this)

    this.$axios.get('/bm/opera/role/findRoleList').then(res => {
      if (res.data.code == 200) {
        this.roleList = res.data.detail
      } else {
        this.$Message.error(res.data.description)
      }
    })

    this.$axios.get('/bm/opera/dept/findAllDeptTree').then(res => {
      if (res.data.code == 200) {
        this.deptData = formatTree(res.data.detail)
      } else {
        this.$Message.error(res.data.description)
      }
    }).catch(err => {
      this.$Message.error('网络错误，请稍后重试！')
    })
  }
}
function formatTree(subdata) {
  let arr = [];
  subdata.forEach((item, index) => {
    let subarr = {};
    subarr = {
      title: item.deptName,
      id: item.id,
      userCount: item.userCount,
      pid: item.pid,
      level: item.level,
      leadName: item.leadName,
      leadId: item.leadId,
      expand: true
    };

    if (item.sonDeptList.length > 0) {
      subarr.children = formatTree(item.sonDeptList);
    }

    arr.push(subarr);
  });

  return arr;
}
</script>
